<template>
  <div>
    <editor-content :editor="editor" />
    <button @click="addTable">添加表格</button>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { Editor, EditorContent } from '@tiptap/vue-3'
import StarterKit from '@tiptap/starter-kit'
import { Node } from '@tiptap/core'
import { ElTable, ElTableColumn } from 'element-plus'
import { h } from 'vue'

// 自定义表格节点
const TableNode = Node.create({
  name: 'table',
  group: 'block',
  content: 'block*',
  tableRole: 'table',
  isolating: true,

  parseHTML() {
    return [
      {
        tag: 'table'
      }
    ]
  },

  renderHTML({ HTMLAttributes }) {
    return ['table', HTMLAttributes, 0]
  },

  addNodeView() {
    return ({ node, getPos }) => {
      const component = {
        props: ['node', 'getPos'],
        template: `
          <el-table :data="node.attrs.data">
            <el-table-column prop="name" label="姓名"></el-table-column>
            <el-table-column prop="age" label="年龄"></el-table-column>
          </el-table>
        `,
        data() {
          return {
            // 这里可以根据实际情况修改数据
            data: this.node.attrs.data
          }
        }
      }

      const vnode = h(component, {
        node,
        getPos
      })

      return {
        dom: document.createElement('div'),
        contentDOM: vnode.el,
        update: newNode => {
          if (newNode.type === this.type) {
            vnode.props.node = newNode
            vnode.component.data = newNode.attrs.data
            return true
          }
          return false
        }
      }
    }
  }
})

// 创建编辑器实例
const editor = ref(
  new Editor({
    extensions: [StarterKit, TableNode]
  })
)

// 添加表格的方法
const addTable = () => {
  const data = [
    { name: '张三', age: 20 },
    { name: '李四', age: 25 }
  ]

  editor.value.commands.insertContent({
    type: 'table',
    attrs: { data }
  })
}
</script>

<style scoped></style>
